package com.entrogy.controller;

import com.entrogy.api.ThdidPersonApi;
import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.*;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.timing.TimingTaskService;
import com.entrogy.utils.*;
import com.entrogy.utils.constants.Constants;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 访客管理控制层接口
 *
 * @Author 许红松
 * @date 2019/6/27 0027 下午 3:32
 */
@RestController
@RequestMapping("/visit")
public class VisitController {

    private static final Logger logger = LoggerFactory.getLogger(VisitController.class);

    @Value("${show.image.url}")
    private String showImage;
    @Value("${image.storage.host}")
    private String imageHost;
    @Value("${image.storage.port}")
    private String hostPort;
    @Autowired
    private VisitService visitService;// 访客信息service接口
    @Autowired
    private ParentService parentService;//家长信息service接口
    @Autowired
    private StudentService studentService;//学生信息service接口
    @Autowired
    private MessageService messageService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private UserService userService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private ThdidPersonApi thdidPersonApi;

    @ApiOperation(value = " 获取访客列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "currentPage", value = "页数", paramType = "query", dataType = "int", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "int", required = false),
            @ApiImplicitParam(name = "uid", value = "用户id", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "selectType", value = "查询类型，0是全部，1是待审核，2是已审核", paramType = "query", dataType = "String", required = false),
    })
    @GetMapping(value = "/getUserList")
    public Result getVisitEntityList(String uid, Integer selectType, int currentPage, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        List<VisitEntity> list = null;
        int totals = 0;
        map.put("selectType", selectType);
        if (StringUtils.isNoneBlank(uid)) {
            if (uid.startsWith("1")) {//老师
                //教师先判断是否是班主任 如果是班主任才可差对应 的家长访问
                UserEntity userEntity = userService.getUserByUid(uid);
                if (userEntity != null) {
                    String classId = userEntity.getClassId();//班级id
                    map.put("schoolCode", userEntity.getSchoolCode());
                    map.put("courseId", classId);
                    map.put("auditUserId", uid);
                    boolean isClassLeader = positionService.checkPosition(uid, 16);
                    if (isClassLeader) {//班主任  查看自己班级下的家长访问
                        totals = visitService.getTeacherVisitTotal(map);
                        PageHelper.startPage(currentPage, pageSize);
                        list = visitService.getTeacherVisit(map);
                    }
                }
            }
            if (uid.startsWith("2")) {//访客
                map.put("parentVisitorId", uid);
                totals = visitService.getListTotal(map);
                PageHelper.startPage(currentPage, pageSize);
                list = visitService.getVisitEntityList(map);
            }
            if (uid.startsWith("3")) {//家长
                map.put("parentVisitorId", uid);
                totals = visitService.getListTotal(map);
                PageHelper.startPage(currentPage, pageSize);
                list = visitService.getVisitEntityList(map);
            }
        }
        PageBean<VisitEntity> visitEntityPageBean = new PageBean<VisitEntity>().pageBeans(list, totals);
        visitEntityPageBean.setBaseImage(showImage);
        return new Result<PageBean>().getResult(401, "查询成功", 1, visitEntityPageBean);

    }

    @ApiOperation(value = " 审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "申请记录", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "uid", value = "用户id", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "sType", paramType = "query", dataType = "int", required = false),
    })
    @GetMapping(value = "/UpdateStype")
    public Result UpdateStype(Integer sType, Integer id, String uid) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNoneBlank(sType.toString())) {
            map.put("sType", sType);
        }
        if (StringUtils.isNoneBlank(id.toString())) { // 不为空
            map.put("id", id);
        }
        int code = visitService.UpdateStype(map);
        if (code == 1) {
            // 根据id查询家长对应的学生id
            VisitEntity visitEntity = visitService.getVisitById(id);
            // 获取实义德后台地址
            Integer schoolCode = userService.getSchoolCodeByUserId(uid);
            String schoolName = schoolService.getSchoolName(schoolCode);
            if (visitEntity != null) {
                ParentVisitorEntity parentVisitorEntity = parentService.getparentById(visitEntity.getParentVisitorId());
                PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(parentVisitorEntity.getParentVisitorPhone());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String[] paramsWeiXin;
                if (null != pubCountEntity && StringUtils.isNoneBlank(pubCountEntity.getOpenid())) {
                    if (sType.equals(2)) {
                        paramsWeiXin = new String[]{"", schoolName, parentVisitorEntity.getParentVisitorName(),
                                dateFormat.format(date), "进校申请:已审核通过", ""};
                        ParentBasicEntity parent = new ParentBasicEntity();
                        parent.setParentVisitorName(parentVisitorEntity.getParentVisitorName())
                                .setParentVisitorBase64(visitEntity.getPhotourl())
                                .setParentVisitorId(visitEntity.getParentVisitorId());
                        // 更新实义德后台家长的照片
                        Map<String, Integer> thdidInfo = thdidPersonApi.updateParentToAll(parent, schoolCode);
                        Integer parentThdidAi16Id = thdidInfo.get("parentThdidAi16Id");
                        Integer parentThdidAi06Id = thdidInfo.get("parentThdidAi06Id");
                        long passStartTime = 0;
                        long passEndTime = 0;
                        try {
                            passStartTime = dateFormat.parse(visitEntity.getStartTime()).getTime() / 1000;
                            passEndTime = dateFormat.parse(visitEntity.getEndTime()).getTime() / 1000;
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        // 推送家长的通行时间
                        thdidPersonApi.pushPersonToAll(parentThdidAi06Id, parentThdidAi16Id, schoolCode, passStartTime, passEndTime, null, "推送家长");
                    } else {
                        paramsWeiXin = new String[]{"", schoolName, parentVisitorEntity.getParentVisitorName(),
                                dateFormat.format(date), "进校申请:未审核通过", ""};
                    }
                    SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/leave/leave?ltype=in&utype=1");
                }
            }
            return new Result<PageBean>().getResult(401, "操作成功", 1, "");
        }
        return new Result<PageBean>().getResult(402, "操作异常", 2, "");
    }

    @ApiOperation(value = "新增审核信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", paramType = "query", value = "用户id", dataType = "String")
    })
    @PostMapping(value = "/addVisitEntity")
    public Result addVisitEntity(@ModelAttribute VisitEntity visitEntity, String uid, Integer studentId) throws ParseException {
        // 判断结束时间是否大于开始时间
        String startTime = visitEntity.getStartTime();
        String endTime = visitEntity.getEndTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);
        if (!startDate.before(endDate)) {
            return new Result<PageBean>().getResult(402, "对不起，进校开始时间必须大于结束时间！", 2, "");
        }
        visitEntity.setParentVisitorId(uid);
        visitEntity.setsType(1);
        ParentVisitorEntity parentVisitorEntity = parentService.getparentById(uid);
        // 家长进校申请推送给相应班主任
        if (parentVisitorEntity != null) {
            // 根据学生id查询学生
            StudentEntity studentEntity = studentService.getStudentById(studentId);
            visitEntity.setName(studentEntity.getStudentName());
            visitEntity.setSchoolCode(parentVisitorEntity.getParentVisitorSchoolCode());
            // 班级id
            int classId = studentEntity.getCourseId();
            // 多职位修改备份
//            UserEntity userEntity = visitService.getUserId(classId, studentEntity.getSchoolCode());
            // 查找该班级班主任
            TeacherBasicInfoEntity teacher = positionService.getClassLeader(classId, studentEntity.getSchoolCode());
            if (teacher == null) {
                return new Result<PageBean>().getResult(402, "对不起，当前选择孩子的班级暂无班主任！", 2, "");
            }
            visitEntity.setAuditUserId(teacher.getTeacherId());
            int code = visitService.addVisitEntity(visitEntity);
            if (code != 1) {
                return new Result<PageBean>().getResult(402, "操作异常", 2, "");
            }
            if (teacher != null) {
                String mobile = teacher.getMobile();//手机号   根据手机号去查询 openid
                PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(mobile);
                if (null != pubCountEntity && StringUtils.isNoneBlank(pubCountEntity.getOpenid())) {
                    String schoolName = schoolService.getSchoolName(studentEntity.getSchoolCode());
                    String[] paramsWeiXin = {"", schoolName, visitEntity.getName(),
                            visitEntity.getStartTime(), "进校申请:" + visitEntity.getVisitContent(), ""};
                    SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/leave/leave?ltype=in&utype=2");
                }
            }
        } else {
            return new Result<PageBean>().getResult(402, "操作异常，家长id不正确", 2, "");
        }
        return new Result<PageBean>().getResult(401, "操作成功", 1, "");
    }

    @ApiOperation(value = "根据id 查询审核详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolCode", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "id", paramType = "query", dataType = "int", required = false)

    })
    @GetMapping(value = "/selectVisitEntityById")
    public Result selectVisitEntityById(String schoolCode, int id) {
        Map<String, Object> map = visitService.selectVisitEntityById(id);
        if (map != null) {
            return new Result<PageBean>().getResult(401, "操作成功", 1, map);
        }
        return new Result<PageBean>().getResult(402, "操作异常", 2, "");
    }


    // 获取历史照片
    @GetMapping(value = "/getExistPhoto")
    @ApiOperation(value = "获取历史照片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uId", paramType = "query", dataType = "String", required = false)
    })
    public Result getExistPhoto(String uId) {
        String url = "";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("showImage", "showImage");
        if (String.valueOf(uId).startsWith("2")) {//教师
            UserEntity userEntity = userService.getUserById(uId);
            if (userEntity != null) {
                jsonObject.put("url", userEntity.getPhoto());
            } else {
                jsonObject.put("url", "");
            }
        } else if (String.valueOf(uId).startsWith("3")) {//家长
            ParentVisitorEntity pvBean = parentService.getparentById(uId);
            if (pvBean != null) {
                jsonObject.put("url", pvBean.getParentVisitorBase64());
            } else {
                jsonObject.put("url", "");
            }
        }
        return new Result<PageBean>().getResult(401, "操作成功", 1, jsonObject);
    }

    @GetMapping(value = "/getVisitorEnableStatus")
    @ApiOperation(value = "获取访客开关状态，0关闭，1开启")
    public Msg getVisitorEnableStatus() {
        Integer visitorEnableStatus = visitService.getVisitorEnableStatus();
        return Msg.success().add("visitorEnableStatus", visitorEnableStatus);
    }
}






